package com.youlv.yl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youlv.yl.dto.MoodLikeDto;
import com.youlv.yl.entity.mood.MoodLike;
import com.youlv.yl.dao.MoodLikeDao;
import com.youlv.yl.service.intf.MoodLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlv.yl.util.TokenUtils;
import com.youlv.yl.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fenghe
 * @since 2022-01-15
 */
@Service
public class MoodLikeServiceImpl extends ServiceImpl<MoodLikeDao, MoodLike> implements MoodLikeService {
    @Autowired
    private MoodLikeDao dao;

    @Override
    public R addLike(MoodLikeDto dto) {
        // 1.入参校验
        System.out.println(dto);
        if(dto != null && dto.getUmid() > 0 && dto.getToken().length() > 0) {
            // 获取用户id
            Long uid = TokenUtils.getUidByToken(dto.getToken());
            // 2.查询点赞对象
            QueryWrapper<MoodLike> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("umid", dto.getUmid());
            MoodLike moodLike = dao.selectOne(queryWrapper);
            // 3.验证之前是否点过赞
            if(moodLike != null) {
                // 点过，再点取消
                dao.deleteById(moodLike.getId());
                // 返回结果
                return R.ok(2);
            } else {
                // 没有过点赞记录， 本次新增
                moodLike = new MoodLike();
                moodLike.setCtime(new Date());
                moodLike.setUid(uid);
                moodLike.setUmid(dto.getUmid());
                dao.insert(moodLike);
                // 返回结果
                return R.ok(1);
            }
        }
        return R.fail("亲，参数有误！");
    }

    @Override
    public R queryById(Long umid) {
        // 入参校验
        if(umid > 0) {
            // 构建对象
            QueryWrapper<MoodLike> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("umid", umid);
            queryWrapper.orderByDesc("ctime");
            // 查询
            return R.ok(dao.selectList(queryWrapper));
        }
        return R.fail("请检查传递的参数");
    }
}
